﻿(function ($) {

    $(function () {

        var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.js", function () {
            $.getScript(scriptbase + "SP.Taxonomy.js", getpopularSearches());
        });
    });

    this.getpopularSearches = function () { 
        var currentId = 'popularSearches-view';
        var itemLimitPopularSearches = getRowLimitFromContentEditorWP(currentId);

        var clientContextPopularSearches = new SP.ClientContext.get_current();
        var popularSearchesList = clientContextPopularSearches.get_web().get_lists().getByTitle('Popular Searches');
        var popularSearchescamlQuery = new SP.CamlQuery();
        popularSearchescamlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Modified' Ascending='FALSE' /></OrderBy></Query><RowLimit>" + itemLimitPopularSearches + "</RowLimit></View>");
        var popularSearchesItems = popularSearchesList.getItems(popularSearchescamlQuery);

        clientContextPopularSearches.load(popularSearchesItems);
        clientContextPopularSearches.executeQueryAsync(
            function () {
                var listEnumeratorpopularSearches = popularSearchesItems.getEnumerator();
                var headerpopularSearches = "<div class=\"popularSearches-title\">Popular Searches</div>";
                var popularSearchesConenttopSites = '';
                while (listEnumeratorpopularSearches.moveNext()) {
                    var popularSearchesitem = listEnumeratorpopularSearches.get_current();

                    var title = popularSearchesitem.get_item("Title");
                    var urlLink = popularSearchesitem.get_item("Url_x0020_Link").get_url();
                    popularSearchesConenttopSites += " <div class=\"popularSearches-content\"><span><a href=\"" + urlLink + "\">" + title + "</a></span></div>";
                }
                //bind data
                $('.popularSearches-content').html(headerpopularSearches + popularSearchesConenttopSites);

            }, function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };
}).call(this, jQuery);